package chat;

import java.net.*;

public class ThisMachine
{
    private ThisMachine()
    {
    }          // private Constructor!

    private static InetAddress[] OurInetAddresses;

    public static String getName()
    {
        if ( !FetchOurInetAddresses() )
            return "";

        return OurInetAddresses[ 0 ].getHostName();
    }

    public static String getIPAddress( int IPindex )
    {
        byte[] zAddress = getNthAddress( IPindex );
        if ( zAddress == null )
            return null;
        String z = "";
        for ( int j = 0 ; j < zAddress.length ; j++ )
            z += "." + (((int) zAddress[ j ]) & 255);
        return z.substring( 1 );
    }

    private static byte[] getNthAddress( int IPindex )
    {
        if ( FetchOurInetAddresses() )
            if ( (0 <= IPindex) && (IPindex < OurInetAddresses.length) )
                return OurInetAddresses[ IPindex ].getAddress();
        return null;
    }

    private static synchronized boolean FetchOurInetAddresses()
    {
        if ( OurInetAddresses != null )
            return true;

        try
        {
            OurInetAddresses = InetAddress.getAllByName( InetAddress.getLocalHost().getHostName() );
        }
        catch ( UnknownHostException e )
        {
            OurInetAddresses = null;
        }

        return (OurInetAddresses != null);
    }
}
